package com.example.module_publish.publish

import android.os.Build
import android.os.Bundle
import android.view.TextureView
import android.view.View
import android.widget.EditText
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.example.lib_common.utils.LoggerUtils
import com.example.module_publish.R
import com.ivideo.avcore.rtmplive.Config
import com.ivideo.avcore.rtmplive.MediaPublisher
import okhttp3.Call
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import java.io.IOException

/**
 * 1:预览
 * 2:输入直播间信息，创建直播间（访问接口）
 * 3.开始推流（rtmp）：采集+编码+推送
 * 4.资源释放
 */
class PublishActivity : AppCompatActivity() {
    private lateinit var mTextureView: TextureView
    private lateinit var et:EditText
    private val mediaPublisher:MediaPublisher by lazy {
        val config = Config.Builder()
            .setFps(30) // 帧率
            .setMaxWidth(720) //视频的最大宽度
            .setMinWidth(320) //视频的最小宽度
//            .setUrl("rtmp://10.161.9.80/live/yaotianxue")//推送的url 服务器下发的
            .build()
        MediaPublisher.newInstance(config)
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_publish2)
        mTextureView = findViewById(R.id.texture_view)
        et = findViewById(R.id.et)
        //动态权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(
                arrayOf(
                    "android.permission.ACCESS_NETWORK_STATE",
                    "android.permission.ACCESS_WIFI_STATE",
                    "android.permission.WRITE_EXTERNAL_STORAGE",
                    "android.permission.READ_EXTERNAL_STORAGE",
                    "android.permission.RECORD_AUDIO",
                    "android.permission.MODIFY_AUDIO_SETTINGS",
                    "android.permission.BLUETOOTH",
                    "android.permission.CAMERA",
                    "android.permission.READ_PHONE_STATE",
                ), 101
            )
        }
        //初始化
        mediaPublisher.init()
    }

    override fun onResume() {
        super.onResume()
        //11111111:预览
        mediaPublisher.initVideoGatherer(this, mTextureView.surfaceTexture)
    }

    fun startPush(view: View) {
        //222222:访问服务器接口创建直播间,得到推拉流地址
        val json = "{\"room_description\": \"事实上\",\"room_name\": \"事实上\"}"
        val requestBody = json.toRequestBody("application/json".toMediaType())
        val client = OkHttpClient.Builder()
            .build()
        val request = Request.Builder()
            .url("http://10.161.9.80:7015/liveRoomAnchor/createLiveRoom")
            .post(requestBody)
            .header("token","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhYSIsImV4cCI6MTc0MTY2Mjg4N30.-IYyzxReCN1NOTnvwzJhEF2_Mnfi1qZ1X8At_NGZo6I")
            .build()
        client.newCall(request).enqueue(object :okhttp3.Callback{
            override fun onFailure(call: Call, e: IOException) {
                LoggerUtils.d("PublishActivity","onFailure ${e.message}")

            }

            override fun onResponse(call: Call, response: Response) {
                LoggerUtils.d("PublishActivity","onResponse ${response.body?.string()}")

                ////3:成功：解析json数据获得推流地址
                //初始化声音采集
                mediaPublisher.initAudioGatherer()
                //初始化编码器
                mediaPublisher.initEncoders()
                //开始采集
                mediaPublisher.startGather()
                //开始编码
                mediaPublisher.startEncoder()
                //开始推送
                mediaPublisher.starPublish("rtmp://10.161.9.80:8066/live/aa")

            }
        })

    }
    //444444:停止
    fun stopPublish(view: View) {
        mediaPublisher.stopPublish()
        mediaPublisher.stopGather()
        mediaPublisher.stopEncoder()
        finish()
    }
    //4444:释放资源
    override fun onDestroy() {
        super.onDestroy()
        mediaPublisher.release()
    }
}